package com.lbiuse.wx.api;

import java.net.URLEncoder;

import com.lbiuse.wx.bean.qrcoe.Qrcode;
import com.lbiuse.wx.util.WxHttpUtils;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;



/**
 * 二维码API
 * 
 * @author jinglupeng.cc
 */
public class QrcodeAPI {

	private static Logger logger = Logger.getLogger(QrcodeAPI.class);

	private static final String CREATE_QRCODE_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";
	private static final String SHOW_QRCODE_URL = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";

	/**
	 * 创建二维码ticket，当seconds为0的或者空时，创建永久有效二维码
	 * 
	 * @param appId
	 *            -第三方用户唯一凭证
	 * @param sceneId
	 *            -场景值ID，临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1--100000）
	 * @param seconds
	 *            -该二维码有效时间，以秒为单位。 最大不超过1800。当为0或者空的时候，则创建永久有效二维码
	 * @return
	 */
	public static Qrcode createQrcode(String appId, Integer sceneId,
			Integer seconds) {
		JSONObject jsonObject = new JSONObject();
		if (sceneId == null || sceneId <= 0) {
			sceneId = 1;
		}
		String action_name = null;
		if (seconds == null || seconds == 0) {
			action_name = "QR_LIMIT_SCENE";
			if (sceneId > 100000) {
				sceneId = 100000;
			}
		} else {
			action_name = "QR_SCENE";
			jsonObject.put("expire_seconds", seconds);
			if (seconds > 1800) {
				seconds = 1800;
			}
			if (seconds <= 0) {
				seconds = 0;
			}
		}
		JSONObject jsonObject2 = new JSONObject();
		JSONObject jsonObject3 = new JSONObject();
		jsonObject3.put("scene_id", sceneId + "");
		jsonObject2.put("scene", jsonObject3);
		jsonObject.put("action_name", action_name);
		jsonObject.put("action_info", jsonObject2);
		String json = jsonObject.toString();
		String token = BaseAPI.getAccessToken(appId);
		if (token == null) {
			logger.error("创建二维码ticket失败，获取AccessToken失败!");
			return new Qrcode(-4, "获取AccessToken失败");
		}
		String url = CREATE_QRCODE_URL.replaceAll("ACCESS_TOKEN", token);
		try {
			return WxHttpUtils.post(url, json, Qrcode.class);
		} catch (Exception e) {
			logger.error("创建二维码ticket失败, 错误信息:" + e.getMessage());
			return new Qrcode(-5, "未知错误");
		}

	}

	/**
	 * 通过ticket换取二维码
	 * 
	 * @param ticket
	 *            -二维码ticket
	 * @return
	 */
	public static String getQrCodeURL(String ticket) {
		try {
			ticket = URLEncoder.encode(ticket, "UTF-8");
			return SHOW_QRCODE_URL.replace("TICKET", ticket);
		} catch (Exception e) {
			logger.error("通过ticket换取二维码失败, 错误信息:" + e.getMessage());
			return null;
		}
	}
}
